import moment from 'moment';
import {  objectAny } from '../options/base';

export function getMoment(
    time?:string|number
){
    return moment(time);
}


export function computedTime(
    sendTime:objectAny
){
    const {send_date:$date,start_time,end_time,splice_time_text}=sendTime;
    const [,addDay]=$date.match(/^\$now([1-9]\d*)*$/);
    const countDay=addDay||0;
    
    const toDay=getMoment().set({hour:countDay*24,minute:0,second:0,millisecond:0})
    
    const {hours:start_h,minutes:start_m,seconds:start_s}=getMoment(start_time).toObject();
    const {hours:end_h,minutes:end_m,seconds:end_s}=getMoment(end_time).toObject();
    const start_time_ms=toDay.set({hour:start_h,minute:start_m,second:start_s,millisecond:0}).valueOf()
    const end_time_ms=toDay.set({hour:end_h,minute:end_m,second:end_s,millisecond:0}).valueOf()

    const formatTimeList=[];

    const nowTime=getMoment();

    for(let i=0;i<splice_time_text.length;i++){
        const {max,min,...others} = splice_time_text[i];

        const {hours:min_h,minutes:min_m,seconds:min_s}=getMoment(min).toObject();
        const {hours:max_h,minutes:max_m,seconds:max_s}=getMoment(max).toObject();

        if($date===`$now`){
            const {hours:now_h}=nowTime.toObject();
            if(min_h<=now_h){
                continue;
            }
        }


        const min_ms=toDay.set({hour:min_h,minute:min_m,second:min_s,millisecond:0}).valueOf()
        const max_ms=toDay.set({hour:max_h,minute:max_m,second:max_s,millisecond:0}).valueOf()
        formatTimeList.push({
            ...others,
            max:max_ms,
            min:min_ms
        })
    }

    const showAliasName:{
        [keyName:string]:string;
    }={
        'undefined':`今天`,
        1:`明天`,
        2:`后天`
    }
    const name=toDay.format(`YYYY-MM-DD`)
    let alias_name=name;
    if(showAliasName[addDay]){
        alias_name=showAliasName[addDay]
    }
    
    return {
        name,
        start_time_ms,
        end_time_ms,
        alias_name,
        formatTimeList
    }
}


export function timePartToggle(min:number,max:number):string{
    min=(+min)
    max=(+max);

    const {hours:start_h,minutes:start_m,seconds:start_s}=getMoment(min).toObject();
    const {hours:end_h}=getMoment(max).toObject();

    const base=getMoment().set({hour:start_h,minute:start_m,second:0,millisecond:0}).format(`YYYY-MM-DD HH:mm`);
    
    return `${base} - ${end_h}:00`
}

export function getToDayTime(time?:any):{
    startTime:number;
    endTime:number;
}{
	const startMs = getMoment(time).set({
		hour: 0,
		minute: 0,
		second: 0,
		millisecond: 0
	}).valueOf()
    const endMs = getMoment(time).set({
		hour: 23,
		minute: 59,
		second: 59,
	}).valueOf()

	return {
        startTime:startMs,
        endTime:endMs
    }
}